import type { Next, Context } from 'koa';
import knex from '../utils/knex';

/**
 * @api {get} /log/retrieve 查询日志
 * @apiVersion 1.0.0
 * @apiDescription create by wuyanshen
 * @apiName retrieve
 * @apiGroup 日志管理
 *
 * @apiUse RequestPagingParam
 * @apiParam {int}     module  系统模块【必填】
 * @apiParam {String}  status  日志状态 (0:正常 1:异常)【必填】
 *
 * @apiUse RequestHeader
 * @apiUse logRetrieveSuccess
 * @apiUse RequestError
 */
async function retrieveAction(ctx: Context, next: Next) {
    try {
        const { page = 1, size = 10, module = '', status } = ctx.query;
        const whereObj: Record<string, any> = {};
        if (module) {
            whereObj.module = module;
        }
        if (status) {
            whereObj.status = status;
        }
        const data = await knex('sys_log')
            .where(whereObj)
            .offset(((page as number) - 1) * (size as number))
            .limit(size as number)
            .orderByRaw('oper_time DESC')
            .select();
        const count = await knex('sys_log').where(whereObj).count();
        ctx.success(
            {
                data,
                count: Object.values(count[0])[0],
            },
            '查询成功',
        );
    } catch (e) {
        ctx.fail(500, '查询失败  ' + e);
    }
    return next();
}

/**
 * @api {delete} /log/clear 清空日志
 * @apiVersion 1.0.0
 * @apiDescription create by wuyanshen
 * @apiName clear
 * @apiGroup 日志管理
 *
 * @apiUse RequestHeader
 * @apiUse deleteSuccess
 * @apiUse RequestError
 */
async function clearAction(ctx: Context, next: Next) {
    try {
        await knex('sys_log').delete();
        ctx.success('', '清空成功');
    } catch (e) {
        ctx.fail(500, '清空成功');
    }
    return next();
}

const logController = {
    retrieveAction,
    clearAction,
};

export default logController;
